<template>
  <div>
    <div v-if="!!robotName" style="background-color: #fff; padding: 16px; margin-bottom: 10px">
      机器人名称：{{ robotName }}
    </div>
    <BaseForm ref="searchForm" type="search" :items="formItems" v-model:form="searchParams" @search="handleSearch">
    </BaseForm>

    <BaseTable
      ref="baseTable"
      :getTableDataFn="wxUserService.getWxUserList"
      :searchParams="searchParams"
      :serial="true"
    >
      <el-table-column prop="wxUserId" label="微信号" />
      <el-table-column prop="wxUserName" label="微信昵称" />
      <el-table-column prop="wxRobotId" :label="type == '1' ? '微信备注' : '群昵称'" />
      <el-table-column prop="url" label="头像">
        <template #default="scope">
          <el-image
            :preview-teleported="true"
            :preview-src-list="[scope.row.url]"
            style="width: 50px; height: 50px"
            v-if="scope.row.url"
            :src="scope.row.url"
          >
          </el-image>
        </template>
      </el-table-column>
      <el-table-column prop="phone" label="微信电话" />
      <!--  <el-table-column prop="wxRobotId" label="地区" /> -->
      <el-table-column prop="selectTagList" label="标签" minWidth="160">
        <template #default="scope">
          <el-tag
            style="margin-left: 2px; margin-right: 2px; margin-top: 5px"
            v-for="item in scope.row.selectTagList"
            type="info"
            :key="item.tagId"
          >
            {{ item.tagName }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="realUserName" label="姓名" />
      <el-table-column prop="realPhone" label="电话" show-overflow-tooltip />
      <el-table-column prop="realAddressInfoList" label="详细家庭地址（用电户号）" minWidth="160">
        <template #default="scope">
          <div
            style="margin-left: 2px; margin-right: 2px; margin-top: 5px"
            v-for="item in scope.row.realAddressInfoList"
            type="info"
            :key="item.tagId"
          >
            <span v-if="getAddress(item).length < 10">{{ getAddress(item) }}</span>
            <el-tooltip v-else class="box-item" effect="dark" :content="getAddress(item)" placement="top">
              <span class="text_ellipsis">{{ getAddress(item) }}</span>
            </el-tooltip>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="操作" fixed="right" width="120">
        <template #default="scope">
          <el-link :underline="false" link type="primary" size="small" @click.prevent="handleEdit(scope.row)"
            >编辑</el-link
          >

          <el-link :underline="false" link type="primary" size="small" @click.prevent="handleLabel(scope.row)"
            >标签设置</el-link
          >
        </template>
      </el-table-column>
    </BaseTable>
    <labelDialog
      v-if="visibleLabelDialog"
      v-model:dialogVisible="visibleLabelDialog"
      :bizId="selectBizId"
      :type="type"
      :handleOk="handleLabelOk"
      :handleCancel="handleLabelCancel"
    ></labelDialog>

    <BaseDialog title="编辑信息" :handleCancel="handleCancel" v-model:dialogVisible="visibleEditForm">
      <el-form class="el-form" ref="addressRef">
        <el-form-item label="姓名" prop="realUserName">
          <el-input v-model="form.realUserName" placeholder="请输入"> </el-input>
        </el-form-item>
        <el-form-item label="电话" prop="realPhone">
          <el-input v-model="form.realPhone" placeholder="请输入手机号，多个用、隔开"> </el-input>
        </el-form-item>
        <el-table border :data="form.realAddressInfoList" :max-height="300" style="width: 100%">
          <el-table-column prop="address" label="详细家庭住址" />
          <el-table-column prop="consumerNumber" label="用电户号" />
          <el-table-column label="操作" fixed="right" width="100">
            <template #default="scope">
              <el-link
                :underline="false"
                link
                type="primary"
                size="small"
                @click.prevent="handleAddEdit(scope.row, scope.$index)"
                >编辑</el-link
              >

              <el-link :underline="false" link type="danger" size="small" @click.prevent="handleDel(scope.$index)"
                >删除</el-link
              >
            </template>
          </el-table-column>
        </el-table>
        <el-button style="width: 100%" type="primary"  @click="handleAddEdit()"
          ><el-icon> <Plus /> </el-icon>添加家庭地址、用电户号</el-button
        >

        <div class="form-btn" style="margin-top: 20px">
          <el-button @click="handleCancel"> 取 消 </el-button>

          <el-button type="primary" :loading="loading" @click="editUser">保存</el-button>
        </div>
      </el-form>
    </BaseDialog>
    <BaseDialog
      :title="formAdd.isNew ? '添加用电户号' : '编辑用电户号'"
      :handleCancel="handleAddCancel"
      v-model:dialogVisible="visibleEditFormAdd"
    >
      <el-form class="el-form" ref="addressRef" v-model="formAdd" label-width="100px">
        <el-form-item label="用户电号" prop="realUserName">
          <el-input v-model="formAdd.consumerNumber" placeholder="请输入用电户号，多个用、隔开"> </el-input>
        </el-form-item>
        <el-form-item label="所属小区">
          <selectPage clearable style="width: 100%" :item="item" v-bind="setAttrs(item)" v-model="formAdd.communityId">
            <!-- <el-option v-for="(option, i) of communityList" :key="i" :label="option.label" :value="option.value" /> -->
          </selectPage>
        </el-form-item>
        <el-form-item label="详细家庭住址" prop="address">
          <el-input
            type="textarea"
            rows="4"
            maxlength="300"
            v-model="formAdd.address"
            placeholder="请输入详细家庭住址，多个用；隔开"
          >
          </el-input>
        </el-form-item>
        <div class="form-btn" style="margin-top: 20px">
          <el-button @click="handleAddCancel"> 取 消 </el-button>

          <el-button type="primary" :loading="loading" @click="editAdd">保存</el-button>
        </div>
      </el-form>
    </BaseDialog>
  </div>
</template>

<script setup lang="ts">
import openMsgBox from '@/hooks/messageBox.js';
import { basicConfigService } from '@/api/basicConfig';
import { wxUserService } from '@/api/wxUser';
import { tagService } from '@/api/tag';
import labelDialog from '@/components/labelDialog.vue';
import selectPage from '@/components/selectPage.vue';
import type { FormInstance } from 'element-plus';
const communityList = ref([]);
const getAllCommunity = () => {
  let options = [];
  basicConfigService.getAllCommunity({ data: {} }).then((res) => {
    let data = res.data.map((e) => {
      return {
        label: e.communityName,
        value: e.communityId,
      };
    });
    options.push(...data);
  });
  communityList.value = options;
};
const robotName = computed(() => {
  return route.query.robotName;
});
const item = ref({
  name: '所属小区',
  key: 'communityId',
  clearable: true,
  type: 'select-page',
  funName: 'getAllCommunity',
  placeholder: '请选择所属小区，单选',
  option: {
    name: 'communityName',
    value: 'communityId',
  },
  firstValue: '',
});
const setAttrs = (params) => {
  const { slot, ...options } = params;
  return { ...options, slot };
};
const router = useRouter();
const route = useRoute();
const bizId = computed(() => {
  return router.currentRoute.value.query.bizId?.toString();
});
const type = computed(() => {
  return router.currentRoute.value.query.type?.toString();
});
const formItems = ref([
  {
    name: '微信号',
    key: 'wxUserId',
    type: 'input',
  },
  {
    name: '微信昵称',
    key: 'wxUserName',
    type: 'input',
  },

  {
    name: type.value == '1' ? '微信备注' : '群昵称',
    key: 'wxUserRemark',
    type: 'input',
  },

  {
    name: '微信电话',
    key: 'phone',
    type: 'input',
  },
  {
    name: '姓名',
    key: 'realUserName',
    type: 'input',
  },
  {
    name: '电话',
    key: 'realPhone',
    type: 'input',
  },
  {
    name: '家庭地址',
    key: 'address',
    type: 'input',
  },
  {
    name: '用电户号',
    key: 'consumerNumber',
    type: 'input',
  },
  {
    name: '标签搜索',
    key: 'tagIds',
    type: 'label',
    selecedList: [],
    tagType: type.value, //1：用户标签
  },
]);
const searchParams = ref({
  wxUserId: '',
  wxUserName: '',
  wxUserRemark: '',
  phone: '',
  realUserName: '',
  realPhone: '',
  address: '',
  tagIds: [],
  bizId: bizId,
  selecedList: undefined,
});
const form = ref({
  realUserName: '',
  realPhone: '',
  realAddressInfoList: [],
  customerId: '',
  wxUserId: '',
});
const loading = ref(false);
onMounted(() => {
  //getAllCommunity();
});

const baseTable = ref(null);
const sortTablekey = ref(1);
const getAddress = (row) => {
  if (row.consumerNumber) return `${row.address}（ ${row.consumerNumber} ）`;
  else return row.address;
};

const handleSearch = (data = { sort: undefined }, e = '') => {
  if (e != 'sort') sortTablekey.value = 0;
  baseTable.value.handleSearch({
    ...searchParams.value,
    bizId: bizId.value,
    tagIds: searchParams.value.selecedList?.map((n) => n.tagId),
    updateTimeOrder: data?.sort,
    selecedList: undefined,
  });
};

const handleLabelOk = (e) => {
  tagService
    .addTagRelation({
      data: {
        bizId: wxUserId.value,
        type: type.value,
        tagIdList: e ? e.map((n) => n.tagId) : [],
      },
    })
    .then((res) => {
      visibleLabelDialog.value = false;
      handleSearch();
    });
};
const handleLabelCancel = () => {
  visibleLabelDialog.value = false;
};
const visibleLabelDialog = ref(false);
const wxUserId = ref('');
const selecedLabelList = ref([]);
const selectBizId = ref('');
const handleLabel = (row) => {
  wxUserId.value = row.wxUserId;
  selectBizId.value = row.wxUserId ? row.wxUserId : row.customerId;
  visibleLabelDialog.value = true;
};
const tableData = ref([]);
const visibleEditForm = ref(false);
const handleEdit = (row) => {
  form.value = JSON.parse(JSON.stringify(row));
  if (!form.value.realAddressInfoList) {
    form.value.realAddressInfoList = [];
  }
  //tableData.value=form.value.
  visibleEditForm.value = true;
};
const addressRef = ref<FormInstance>();
const editUser = () => {
  loading.value = true;
  wxUserService
    .editWxUser({
      data: {
        customerId: form.value.customerId,
        wxUserId: form.value.wxUserId,
        realUserName: form.value.realUserName,
        realPhone: form.value.realPhone,
        sourceType: 1,
        realAddressInfoList: form.value.realAddressInfoList,
      },
    })
    .then((res) => {
      loading.value = false;
      visibleEditForm.value = false;
      handleSearch();
    })
    .catch(() => {
      loading.value = false;
    });
};
const handleCancel = () => {
  visibleEditForm.value = false;
};
const handleDel = (index) => {
  openMsgBox(
    {},
    () => {
      form.value.realAddressInfoList.splice(index, 1);
    },
    () => {
      //handleSearch()
    },
  );
};
const formAdd = ref({
  consumerNumber: '',
  communityId: '',
  communityName: '',
  address: '',
  isNew: 0,
});
const visibleEditFormAdd = ref(false);
const temIndex = ref(0);
const handleAddEdit = (row?, index?) => {
  if (row) {
    formAdd.value = { ...row, isNew: 0 };
    temIndex.value = index;
  } else {
    formAdd.value = {
      consumerNumber: '',
      communityId: '',
      communityName: '',
      address: '',
      isNew: 1,
    };
  }
  visibleEditFormAdd.value = true;
};
const handleAddCancel = () => {
  visibleEditFormAdd.value = false;
};
const editAdd = () => {
  if (!formAdd.value.consumerNumber && !formAdd.value.address) {
    ElMessage({
      message: '用电户号和详细家庭住址至少必填一个',
      type: 'error',
    });
    return;
  }
  if (formAdd.value.isNew) {
    form.value.realAddressInfoList.push(formAdd.value);
  } else {
    form.value.realAddressInfoList.splice(temIndex.value, 1, formAdd.value);
  }
  visibleEditFormAdd.value = false;
};
</script>

<style lang="less" scoped></style>
